<template>
  <div v-if="showProgress" class="voice-task-progress" ref="progressPanel">
    <div class="progress-container">
      <!-- 进度头部 -->
      <div class="progress-header" @mousedown="startDrag">
        <div class="header-left">
          <h4 class="progress-title">语音处理进度</h4>
          <span v-if="taskId" class="task-id">任务ID: {{ taskId }}</span>
        </div>
        <div class="header-right">
          <el-button 
            v-if="canCancel" 
            size="small" 
            type="danger" 
            @click="handleCancel"
            :loading="cancelling"
          >
            取消任务
          </el-button>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-bar-container">
        <div class="progress-bar">
          <div 
            class="progress-fill" 
            :style="{ width: progress + '%' }"
            :class="progressClass"
          ></div>
        </div>
        <span class="progress-text">{{ progress }}%</span>
      </div>

      <!-- 步骤指示器 -->
      <div class="step-indicators">
        <div 
          v-for="step in steps" 
          :key="step.key"
          class="step"
          :class="getStepClass(step.key)"
        >
          <el-icon class="step-icon">
            <component :is="step.icon" />
          </el-icon>
          <span class="step-name">{{ step.name }}</span>
          <div v-if="getStepClass(step.key).includes('active')" class="step-loading">
            <el-icon class="is-loading">
              <Loading />
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 状态消息 -->
      <div class="status-message">
        <el-icon class="message-icon">
          <component :is="statusIcon" />
        </el-icon>
        <span class="message-text">{{ taskMessage || '准备中...' }}</span>
      </div>

      <!-- 识别文本预览 -->
      <div v-if="recognizedText" class="recognized-text">
        <div class="text-label">识别文本:</div>
        <div class="text-content">{{ recognizedText }}</div>
      </div>

      <!-- AI回复预览 -->
      <div v-if="aiReply" class="ai-reply">
        <div class="reply-label">AI回复:</div>
        <div class="reply-content">{{ aiReply }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { ElButton, ElIcon, ElMessage } from 'element-plus'
import { 
  Microphone, 
  User, 
  Bell, 
  FolderOpened, 
  Loading,
  Check,
  Close,
  Warning
} from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'

const chatStore = useChatStore()

// Props
interface Props {
  showProgress?: boolean
  canCancel?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showProgress: true,
  canCancel: true
})

// Emits
const emit = defineEmits<{
  cancel: []
}>()

// 状态
const cancelling = ref(false)

// 拖拽相关
const progressPanel = ref<HTMLElement>()
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
const panelPosition = ref({ x: 0, y: 0 })

// 计算属性
const taskId = computed(() => chatStore.currentTaskId)
const progress = computed(() => chatStore.taskProgress)
const taskStatus = computed(() => chatStore.taskStatus)
const currentStep = computed(() => chatStore.currentStep)
const taskMessage = computed(() => chatStore.taskMessage)

// 步骤定义
const steps = [
  { key: 'ASR', name: '语音识别', icon: Microphone },
  { key: 'AI', name: 'AI对话', icon: User },
  { key: 'TTS', name: '语音合成', icon: Bell },
  { key: 'STORAGE', name: '存储完成', icon: FolderOpened }
]

// 进度条样式类
const progressClass = computed(() => {
  switch (taskStatus.value) {
    case 'PROCESSING':
      return 'processing'
    case 'COMPLETED':
      return 'completed'
    case 'FAILED':
      return 'failed'
    default:
      return 'pending'
  }
})

// 状态图标
const statusIcon = computed(() => {
  switch (taskStatus.value) {
    case 'PROCESSING':
      return Loading
    case 'COMPLETED':
      return Check
    case 'FAILED':
      return Close
    default:
      return Warning
  }
})

// 识别文本和AI回复（从消息中获取）
const recognizedText = computed(() => {
  const userMessage = chatStore.messages
    .filter(m => m.senderType === 1)
    .pop()
  return userMessage?.content || ''
})

const aiReply = computed(() => {
  const aiMessage = chatStore.messages
    .filter(m => m.senderType === 2)
    .pop()
  return aiMessage?.content || ''
})

// 获取步骤样式类
const getStepClass = (stepKey: string) => {
  const classes = ['step']
  
  if (stepKey === currentStep.value) {
    classes.push('active')
  } else if (isStepCompleted(stepKey)) {
    classes.push('completed')
  } else {
    classes.push('pending')
  }
  
  return classes
}

// 判断步骤是否完成
const isStepCompleted = (stepKey: string) => {
  const stepOrder = ['ASR', 'AI', 'TTS', 'STORAGE']
  const currentIndex = stepOrder.indexOf(currentStep.value || '')
  const stepIndex = stepOrder.indexOf(stepKey)
  return stepIndex < currentIndex
}

// 取消任务
const handleCancel = async () => {
  try {
    cancelling.value = true
    await chatStore.cancelCurrentTask()
    emit('cancel')
    ElMessage.info('任务已取消')
  } catch (error) {
    console.error('取消任务失败:', error)
    ElMessage.error('取消任务失败')
  } finally {
    cancelling.value = false
  }
}

// 拖拽功能
const startDrag = (event: MouseEvent) => {
  if (!progressPanel.value) return
  
  isDragging.value = true
  const rect = progressPanel.value.getBoundingClientRect()
  dragOffset.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  }
  
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  event.preventDefault()
}

const onDrag = (event: MouseEvent) => {
  if (!isDragging.value || !progressPanel.value) return
  
  panelPosition.value = {
    x: event.clientX - dragOffset.value.x,
    y: event.clientY - dragOffset.value.y
  }
  
  // 限制在视窗内
  const maxX = window.innerWidth - progressPanel.value.offsetWidth
  const maxY = window.innerHeight - progressPanel.value.offsetHeight
  
  panelPosition.value.x = Math.max(0, Math.min(panelPosition.value.x, maxX))
  panelPosition.value.y = Math.max(0, Math.min(panelPosition.value.y, maxY))
  
  progressPanel.value.style.left = panelPosition.value.x + 'px'
  progressPanel.value.style.top = panelPosition.value.y + 'px'
  progressPanel.value.style.transform = 'none'
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 生命周期
onMounted(() => {
  // 初始化位置为屏幕中央
  if (progressPanel.value) {
    const rect = progressPanel.value.getBoundingClientRect()
    panelPosition.value = {
      x: (window.innerWidth - rect.width) / 2,
      y: (window.innerHeight - rect.height) / 2
    }
  }
})

onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
})
</script>

<style scoped>
.voice-task-progress {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  min-width: 400px;
  max-width: 500px;
  animation: slideIn 0.3s ease-out;
  user-select: none;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

.progress-container {
  padding: 24px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  cursor: move;
  padding: 8px;
  margin: -8px -8px 12px -8px;
  border-radius: 8px;
  transition: background-color 0.2s ease;
}

.progress-header:hover {
  background-color: #f5f5f5;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.progress-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.task-id {
  font-size: 12px;
  color: #6b7280;
  font-family: monospace;
}

.progress-bar-container {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease, background-color 0.3s ease;
}

.progress-fill.pending {
  background: #d1d5db;
}

.progress-fill.processing {
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  animation: pulse 2s infinite;
}

.progress-fill.completed {
  background: #10b981;
}

.progress-fill.failed {
  background: #ef4444;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.progress-text {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  min-width: 40px;
  text-align: right;
}

.step-indicators {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 0 8px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  position: relative;
  flex: 1;
}

.step-icon {
  width: 24px;
  height: 24px;
  color: #9ca3af;
  transition: color 0.3s ease;
}

.step-name {
  font-size: 12px;
  color: #6b7280;
  text-align: center;
  transition: color 0.3s ease;
}

.step-loading {
  position: absolute;
  top: -4px;
  right: -4px;
}

.step.active .step-icon {
  color: #3b82f6;
}

.step.active .step-name {
  color: #1f2937;
  font-weight: 600;
}

.step.completed .step-icon {
  color: #10b981;
}

.step.completed .step-name {
  color: #10b981;
  font-weight: 600;
}

.status-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 8px;
  margin-bottom: 16px;
}

.message-icon {
  color: #6b7280;
}

.message-text {
  font-size: 14px;
  color: #374151;
}

.recognized-text,
.ai-reply {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 3px solid #3b82f6;
}

.text-label,
.reply-label {
  font-size: 12px;
  font-weight: 600;
  color: #6b7280;
  margin-bottom: 4px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.text-content,
.reply-content {
  font-size: 14px;
  color: #1f2937;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .voice-task-progress {
    min-width: 320px;
    max-width: 90vw;
  }
  
  .progress-container {
    padding: 16px;
  }
  
  .step-indicators {
    gap: 4px;
  }
  
  .step-name {
    font-size: 11px;
  }
}
</style>
